package com.javatest.ajax.app2.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.javatest.ajax.app2.bean.ShoppingCart;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2018-09-03 下午4:55
 */
public class AddToCartServlet extends HttpServlet {
    private static final long serialVersionUID = 552665297039870380L;
    private static final Logger LOGGER = LoggerFactory.getLogger(AddToCartServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取请求参数：id,price
        String bookName = req.getParameter("id");
        int price = Integer.valueOf(req.getParameter("price"));

        //2.获取购物车对象
        HttpSession session = req.getSession();
        ShoppingCart shoppingCart = (ShoppingCart) session.getAttribute("sc");
        if (shoppingCart == null) {
            shoppingCart = new ShoppingCart();
            session.setAttribute("sc", shoppingCart);
        }
        //3.把点击的对象加入到购物车中
        shoppingCart.addToCart(bookName, price);
        //4.准备响应的json对象
//        StringBuilder builder = new StringBuilder();
//        builder.append("{")
//                .append("\"bookName\":\"").append(bookName).append("\",")
//                .append("\"totalNumber\":").append(shoppingCart.getTotalBookNumber()).append(",")
//                .append("\"totalMoney\":").append(shoppingCart.getTotalMoney())
//                .append("}");
        //5.响应json对象
        resp.setContentType("text/javascript");
//        resp.getWriter().print(builder.toString());
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(shoppingCart);
        LOGGER.info(json);
        resp.getWriter().print(json);
    }
}
